package com.legal.service.user.impl;

import com.legal.service.user.CaptchaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {

    private final RedisTemplate<String, String> redisTemplate;

    private static final long CAPTCHA_EXPIRE = 2; // 验证码有效期（分钟）
    private static final String CAPTCHA_KEY_PREFIX = "captcha:"; // Redis key 前缀

    /**
     * 生成验证码并存入 Redis List
     */
    @Override
    public String getCaptcha(String phoneNumber) {
        String captcha = RandomStringUtils.randomNumeric(4); // 4位数字验证码
        log.info("生成验证码: {}", captcha);

        // 使用 List 存储
        String key = CAPTCHA_KEY_PREFIX + phoneNumber;
        redisTemplate.opsForList().rightPush(key, captcha);

        // 设置过期时间
        redisTemplate.expire(key, CAPTCHA_EXPIRE, TimeUnit.MINUTES);

        // 验证存储结果（调试用）
        String storedCode = redisTemplate.opsForList().index(key, 0);
        log.info("取出的验证码: {}", storedCode);

        return captcha;
    }

    /**
     * 验证码校验（从 List 中获取最新验证码）
     */
    @Override
    public boolean validateCaptcha(String phoneNumber, String inputCode) {
        String key = CAPTCHA_KEY_PREFIX + phoneNumber;

        // 获取 List 中最新（最后）的验证码
        String storedCode = redisTemplate.opsForList().index(key, -1);

        log.info("输入的验证码: {}", inputCode);
        boolean isValid = inputCode.equals(storedCode);
        log.info("验证码校验结果: {}", isValid);

        return isValid;
    }

    /**
     * 删除验证码 List
     */
    @Override
    public void deleteCaptcha(String phoneNumber) {
        redisTemplate.delete(CAPTCHA_KEY_PREFIX + phoneNumber);
    }
}
